<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 用户促销模型
 * @author www.dingwei.cn
 */

class ConsumerPromotionModel extends MY_Model{
	
	public $tbBonus = 'admin_bonus'; //平台红包
	public $tbBonusLog = 'consumer_bonus_log';//消费者红包记录
	public $tbCashCoupon= 'consumer_cash_coupon';//消费者代金劵记录
    public $tbUser = 'consumer'; // 用户
    public $tbOrder = 'consumer_order'; // 订单
    public $tbMerchantShop = 'merchant_shop'; //
    public $tbMerchantBonus = 'merchant_bonus'; //
    
	public $BONUS_TYPE = array(
	    '1' => '分享发放',
	    '2' => '按用户发放',
	    '3' => '注册发放',
    );

	/**
	 * 获取红包记录
	 * @param integer $consumerId 消费者id
	 * @param number $page	分页
	 * @param number $status	1-未使用 2-使用 3-已过期
	 * @return array|array[]|number[]|unknown[]
	 */
	public function appGetBonusLogList($consumerId,$status,$page = 1,$total = FALSE,$condition = 0, $wx = false){
// 		echo strtotime('2017-12-31');
		$this->db
		->select('log.id,b.name,log.money,log.addtime,b.condition,b.type,b.use_end_time,log.status')
		->join($this->tbBonus.' b','b.id = log.bonus_id','left')
		->where('log.consumer_id',$consumerId); //消费者
		
		if ($status == 1){
			//未使用 未过期
			$this->db
			->where('log.status',1)//状态
			->where('b.use_end_time >',time());//未过期
		}else if($status == 2){
			//已使用
			$this->db->where('log.status',2);//状态 
		}elseif ($status == 3){
			//过期
			$this->db
			->where('log.status',1)//未使用
			->where('b.use_end_time <=',time());//过期
		}
		

		//只获取数量---------------------------------------------
		if ($total){
			
			return $this->count($this->tbBonusLog.' log');
		}
		//消费金额大于等于条件，的红包列表---------------------------------------
		if ($condition){
			
			$this->db->where('b.condition <=',$condition)
                     ->order_by('log.money desc');

			$tA = $this->getAll($this->tbBonusLog.' log');
		}else{
			//获取列表---------------------------------------------
			$tA = $this->appPage($this->tbBonusLog.' log', $page);
			$tA = $tA['list'];
		}
//		$wxData[] = array('title' => '暂不使用','value' => [0, 0.00]);
        $wxData = array();
		foreach ($tA as $k=>$v){
			$tA[$k]['time'] = "0";
			if ($status == 1){
				$tA[$k]['time'] = (string)floor(($v['use_end_time'] - time())/3600/24);
			}
			elseif ($status == 3){
				$tA[$k]['status'] = "3";
			}
			$tA[$k]['money'] = (string)(round($v['money'],1));
			$tA[$k]['condition'] = '满'.(int)$v['condition'].'元可使用';
            $wxData[] =  array('title' => $tA[$k]['condition'].'('.$v['money'].')','value' => [$v['id'], $v['money']]);
		}
		
		return $wx == true?$wxData:$tA;
	}

    /**获取用户红包明细
     * @param $consumerId
     * @param int $status
     * @return array
     */
	public function getUserBonusLogList($consumerId,$status=0){
        $status = intval(get('status'));
        $name = trim(get('name'));
        $sendDateFrom = strtotime(get('addtime_from'));
        $sendDateTo = strtotime(get('addtime_to'));

		$this->db
		->select('log.id,b.name,log.money,log.addtime,b.condition,b.type,b.use_end_time,log.status,log.order_id')
		->join($this->tbBonus.' b','b.id = log.bonus_id','left')
		->where('log.consumer_id',$consumerId); //消费者

		if ($status == 1){
			//未使用 未过期
			$this->db
			->where('log.status',1)//状态
			->where('b.use_end_time >',time());//未过期
		}else if($status == 2){
			//已使用
			$this->db->where('log.status',2);//状态
		}elseif ($status == 3){
			//过期
			$this->db
			->where('log.status',1)//未使用
			->where('b.use_end_time <=',time());//过期
		}
        if($name){
            $this->db->like('b.name', $name);
        }
        if($sendDateFrom){
            $this->db->where('log.addtime >=', $sendDateFrom);
        }
        if($sendDateTo){
            $this->db->where('log.addtime <', strtotime('+1day', $sendDateTo));
        }
        $tA = $this->pagination($this->tbBonusLog.' log');

		return $tA;
	}
	
	/**
	 * 获取优惠券记录
	 * @param integer $consumerId 消费者id
	 * @param number $status	1-未使用 2-使用 3-已过期
	 * @param number $page	分页
	 * @return array|array[]|number[]|unknown[]
	 */
	public function appGetCouponLogList($consumerId,$status,$page = 1,$total = FALSE,$condition = 0,$merchantId = 0,$wx = false){
		
		$this->db
		->select('log.id,log.merchant_id,log.money,log.use_end_time,log.condition,log.status')
		->where('log.consumer_id',$consumerId); //消费者
		
		if ($status == 1){
			//未使用 未过期
			$this->db
			->where('log.status',1)//状态
			->where('log.use_end_time >',time());//未过期
		}else if($status == 2){
			//已使用
			$this->db->where('log.status',2);//状态
		}elseif ($status == 3){
			//过期
			$this->db
			->where('log.status',1)//未使用
			->where('log.use_end_time <=',time());//过期
		}
		
		if ($condition && $merchantId){
			//消费金额大于等于条件，的红包列表
			//获取该商家的代金劵
			$this->db->where('log.condition <=',$condition);
			$this->db->where('log.merchant_id',$merchantId);
			$tA = $this->getAll($this->tbCashCoupon.' log');
//            $wxData[] = array('title' => '暂不使用','value' => [0, 0.00]);
            $wxData = array();
			foreach ($tA as $k=>$v){

				$tA[$k]['time'] = "0";
				
				if ($status == 1){
					$tA[$k]['time'] = (string)floor(($v['use_end_time'] - time())/3600);
				}
				elseif ($status == 3){
					$tA[$k]['status'] = "3";
				}
				$tA[$k]['money'] = round($v['money'],2);
				$tA[$k]['condition'] = '满'.round($v['condition'],2).'元可使用';
                $wxData[] =  array('title' => $tA[$k]['condition'].'('.$v['money'].')','value' => [$v['id'], $v['money']]);
			}
			return $wx == true?$wxData:$tA;
		}

		
		if ($total){
			//获取总数
			return $this->count($this->tbCashCoupon.' log');
		}
		
		$tA = $this->appPage($this->tbCashCoupon.' log', $page,true);
		
		//p($this->db->last_query());
		foreach ($tA['list'] as $k=>$v){
			$tA['list'][$k]['time'] = "0";
			
			if ($status == 1){
				$tA['list'][$k]['time'] = (string)floor(($v['use_end_time'] - time())/3600);
			}
			elseif ($status == 3){
				$tA['list'][$k]['status'] = "3";
			}
			$tA['list'][$k]['money'] = round($v['money'],2);
			$tA['list'][$k]['condition'] = '满'.round($v['condition'],2).'元可使用';
		}
		
		return $tA['list'];
	}
	
	/**
     * 后台获取红包记录
     */
	public function adminPcGetBonusList(){
        $type = (int)get('type');
        $status = (int)get('status');
        $name = trim(get('name'));
        $money = trim(get('money'));
        $sendNumber = trim(get('send_number'));
        $surplusNumber = trim(get('surplus_number'));
        $useEndDateFrom = strtotime(get('use_end_date_from'));
        $useEndDateTo = strtotime(get('used_time_date_to'));
        $sendDateFrom = strtotime(get('send_date_from'));
        $sendDateTo = strtotime(get('send_date_to'));
        $iSortCol_0 = (int)get('iSortCol_0');//针对某一列进行排序
        $sSortDir_0 = trim(get('sSortDir_0'));//排序方式，值为"asc"或者"desc"

        if ($name){
            $this->db->like(array('name' => $name));
        }
        if ($type){
            $this->db->where(array('type' => $type));
        }
        if ($status){
            $this->db->where(array('status' => $status));
        }
        if ($sendNumber){
            $this->db->like(array('send_number' => $sendNumber));
        }
        if ($money){
            $this->db->like(array('money' => $money));
        }
        if ($surplusNumber){
            $this->db->like(array('surplus_number' => $surplusNumber));
        }
        if($useEndDateFrom){
            $this->db->where('use_end_time >=', $useEndDateFrom);
        }
        if($useEndDateTo){
            $this->db->where('use_end_time <', strtotime('+1day', $useEndDateTo));
        }
        if($sendDateFrom){
            $this->db->where('addtime >=', $sendDateFrom);
        }
        if($sendDateTo){
            $this->db->where('addtime <', strtotime('+1day', $sendDateTo));
        }

        if ($iSortCol_0 == 2){
            $this->db->order_by('money', $sSortDir_0); // 面额
        }else if($iSortCol_0 == 3){
            $this->db->order_by('condition', $sSortDir_0); // 消费金额
        }else if($iSortCol_0 == 4){
            $this->db->order_by('send_number', $sSortDir_0); // 发放总数量
        }else if($iSortCol_0 == 5){
            $this->db->order_by('surplus_number', $sSortDir_0); // 剩余数量
        }else if($iSortCol_0 == 6){
            $this->db->order_by('use_end_time', $sSortDir_0); // 截至时间
        }else if($iSortCol_0 == 7){
            $this->db->order_by('addtime', $sSortDir_0); // 添加时间
        }else{
            $this->db->order_by('addtime desc');
        }

        $this->db->where('status > 1');
	    $data = $this->pagination($this->tbBonus);
	    return $data;
    }

    /**
     * @param null $key
     * @param bool $show
     * @return string
     */
    public function getStatus($key = null, $show = false){
        $config = array(
            '2' => '发布',
            '3' => '未发布',
        );
        if($key === null){
            return $config;
        }

        if($key !== null && ! isset($config[$key])){
            return '';
        }

        if( ! $show ){
            return $config[$key];
        }

        if ($key == 1) {
            return '';
        } else if ($key == 2) {
            return '<span class="label label-success">'.$config[$key].'</span>';
        } else if ($key == 3) {
            return '<span class="label label-danger">' . $config[$key] . '</span>';
        }
    }

    /**
     * 保存数据
     * @param $data
     * @param $id
     * @return bool|int
     * @author heyu
     */
    public function save($data, $id = 0,$batch = false){
        if($batch){
            return $this->updateBatch($this->tbBonus, $data, 'id');
        }
        if($id){
            $this->db->where('id', $id);
            return $this->update($this->tbBonus, $data);
        }

        return $this->insert($this->tbBonus, $data);
    }

    /**
     * 查看红包详情
     * @param $id
     * @return array
     * @author heyu
     */
    public function getInfo($id){
        if (!$id){
            return array();
        }
        $this->db->where(array('id' => $id));
        $tA = $this->getOne($this->tbBonus);
        $tA['type_name'] = $this->BONUS_TYPE[$tA['type']];
        $tA['send_start_time'] = dateFormat($tA['send_start_time']);
        $tA['send_end_time'] = dateFormat($tA['send_end_time']);
        $tA['use_start_time'] = dateFormat($tA['use_start_time']);
        $tA['use_end_time'] = dateFormat($tA['use_end_time']);
        return $tA;
    }

    /**
     * 删除红包
     * @param $id
     * @return bool
     * @author heyu
     */
    public function deleteBonus($id){
        if (!$id){
            return false;
        }
        $this->db->where(array('id' => $id));
        return $this->delete($this->tbBonus);
    }

    /**
     * 保存红包记录
     * @param array     $data
     * @param int       $id
     * @param bool      $isBatch         批量保存
     * @return bool|int
     * @author heyu
     */
    public function saveBonusLog($data, $id = 0, $isBatch = false){
        if ($isBatch){
            return $this->insertBatch($this->tbBonusLog, $data);
        }
        if($id){
            $this->db->where('id', $id);
            return $this->update($this->tbBonusLog, $data);
        }

        return $this->insert($this->tbBonusLog, $data);
    }

    /**
     * 批量保存红包信息
     * @param unknown $data
     * @param unknown $bonusIds
     * @return boolean
     * @author zyl
     */
    public function saveBatchBonusLog($data,$bonusIds){
    	if ($bonusIds){
    		$this->db->where_in('id',$bonusIds);
    		$query =  $this->update($this->tbBonusLog, $data);
    		return $query === false ? false:true;
    	}
    	
    	return false;
    }
    
    /**
     * 批量保存代金劵信息
     * @param unknown $data
     * @param unknown $bonusIds
     * @return boolean
     * @author zyl
     */
    public function saveBatchCouponLog($data,$couponIds = array()){
    	if ($couponIds){
    		$this->db->where_in('id',$couponIds);
    		$query = $this->update($this->tbCashCoupon, $data);
    		return $query === false ? false:true;
    	}else{
    		return $this->insertBatch($this->tbCashCoupon, $data);
    	}
    	
    	return false;
    }
    
    /**
     * 红包记录列表
     */
    public function adminPcGetBonusLogList(){
        $bonusId = (int)get('bonus_id');
        $status = (int)get('status');
        $consumer = trim(get('consumer'));
        $money = trim(get('money'));
        $orderCode = trim(get('order_code'));
        $code = trim(get('code'));
        $usedTimeDateFrom = strtotime(get('used_time_date_from'));
        $usedTimeDateTo = strtotime(get('used_time_date_to'));
        $sendDateFrom = strtotime(get('send_date_from'));
        $sendDateTo = strtotime(get('send_date_to'));
        $iSortCol_0 = (int)get('iSortCol_0');//针对某一列进行排序
        $sSortDir_0 = trim(get('sSortDir_0'));//排序方式，值为"asc"或者"desc"

        if ($bonusId){
            $this->db->where(array('bl.bonus_id' => $bonusId));
        }
        if ($status){
            $this->db->where(array('bl.status' => $status));
        }
        if ($consumer){
            $this->db->like(array('u.nickname' => $consumer));
        }
        if ($money){
            $this->db->like(array('bl.money' => $money));
        }
        if ($orderCode){
            $this->db->like(array('o.code' => $orderCode));
        }
        if ($code){
            $this->db->like(array('bl.code' => $code));
        }
        if($usedTimeDateFrom){
            $this->db->where('bl.usedtime >=', $usedTimeDateFrom);
        }
        if($usedTimeDateTo){
            $this->db->where('bl.usedtime <', strtotime('+1day', $usedTimeDateTo));
        }
        if($sendDateFrom){
            $this->db->where('bl.addtime >=', $sendDateFrom);
        }
        if($sendDateTo){
            $this->db->where('bl.addtime <', strtotime('+1day', $sendDateTo));
        }

        if ($iSortCol_0 == 1){
            $this->db->order_by('bl.money', $sSortDir_0); // 领取金额
        }else if($iSortCol_0 == 5){
            $this->db->order_by('bl.usedtime', $sSortDir_0); // 使用时间
        }else if($iSortCol_0 == 6){
            $this->db->order_by('bl.addtime', $sSortDir_0); // 添加时间
        }else{
            $this->db->order_by('bl.addtime desc');
        }

        $this->db->select('bl.code,bl.money,bl.status,bl.usedtime,bl.addtime,u.nickname as consumer,u.mobile as consumer_mobile,o.code as order_code')
            ->join($this->tbUser.' u', 'u.id=bl.consumer_id')
            ->join($this->tbOrder.' o', 'o.id=bl.order_id', 'left');

        $data = $this->pagination($this->tbBonusLog.' bl');
        return $data;
    }

    /**
     * 获取商家的红包
     * @return unknown[]
     */
    public function homeGetBonusList($page = 1){
    	
    	$this->db->select('b.id,b.pic,b.number,IFNULL(b.receive_number,0) as receive_number,b.merchant_id,ms.shop_name')
    	->where('b.start_time <=',time())//当前时间大于等雨开始时间
    	->where('b.end_time >',time())//当前时间小于结束时间
    	->where('b.status',3)
    	->join($this->tbMerchantShop.' ms','ms.merchant_id = b.merchant_id');//进行中
    	
    	$tA = $this->appPage($this->tbMerchantBonus.' b',$page);

    	foreach ($tA['list'] as $k=>$v){
    		$tA['list'][$k]['pic'] = getImage($v['pic'],'xs');
    	}
    	return $tA['list'];
    }
    
    /**
     * 批量获取红包
     * @param unknown $bonusIds 红包ids
     * @param number $consumerId 消费者id
     * @return array|array
     * @author zyl
     */
    public function getBonusByIds($bonusIds,$consumerId = 0){
    	
    	if ( ! $bonusIds && ! $consumerId){
    		return array();
    	}
    	if ($consumerId){
    		$this->db->where('log.consumer_id',$consumerId);
    	}
    	
    	$this->db->select('log.id,log.money,b.condition')
    	->join($this->tbBonus.' b','b.id=log.bonus_id','left')
    	->where('b.use_start_time <=',time())//当前时间大于等雨开始时间
    	->where('b.use_end_time >',time())//当前时间小于结束时间
    	->where('log.status',1)//未使用过
    	->where_in('log.id',$bonusIds);//未使用过
    	
    	$tA = $this->getAll($this->tbBonusLog.' log');
 
    	$tData = array();
    	foreach ($tA as $k=>$v){
    		$tData[$v['id']] = $v;
    	}
    	return $tData;
    }
    
    /**
     * 批量获取红包
     * @param unknown $bonusIds 红包ids
     * @param number $consumerId 消费者id
     * @return array|array
     * @author zyl
     */
    public function getCouponByIds($couponIds,$consumerId = 0){
    	
    	if ( ! $couponIds&& ! $consumerId){
    		return array();
    	}
    	if ($consumerId){
    		$this->db->where('consumer_id',$consumerId);
    	}
    	
    	$this->db->select('id,money,condition')
    	->where('use_end_time >',time())//当前时间小于结束时间
    	->where('status',1)//未使用过
    	->where_in('id',$couponIds);//未使用过
    	
    	$tA = $this->getAll($this->tbCashCoupon);
    	
    	$tData = array();
    	foreach ($tA as $k=>$v){
    		$tData[$v['id']] = $v;
    	}
    	return $tData;
    }

    /**
     * 获取红包总成本
     * @param int $startTime
     * @param int $endTime
     * @param int $page
     * @param int $pageNumber
     * @return array
     * @author heyu
     */
    public function getTotalBonusLog($startTime = 0, $endTime = 0, $page = 0, $pageNumber = 0){
        if ($startTime){
            $this->db->where('addtime >= '.$startTime);
        }
        if ($endTime){
            $this->db->where('addtime < '.$endTime);
        }
        $this->db->select('sum(money) as money,FROM_UNIXTIME(addtime,"%Y-%m") as time')
            ->where(array('status' => 2))
            ->group_by('time');
        $data = array();
        if ($page && $pageNumber) {
            $tA = $this->appPage($this->tbBonusLog, $page, false, $pageNumber);
            if (!empty($tA['list'])){
                foreach ($tA['list'] as $v){
                    $data[$v['time']] = $v;
                }
            }
        }else{
            $tA = $this->pagination($this->tbBonusLog);
            if (!empty($tA['data'])){
                foreach ($tA['data'] as $v){
                    $data[$v['time']] = $v;
                }
            }
        }

        unset($tA);
        return $data;
    }

    /**
     * 获取红包状态
     * @param $key
     * @param bool $show
     * @return array|mixed|string
     * @author heyu
     */
    public function getBonusLogStatus($key, $show = false){
        $config = array(1 => '未使用', 2 => '已使用', 3 => '已失效');
        if( ! $key){
            return $config;
        }

        if($key && ! isset($config[$key])){
            return '';
        }

        if( ! $show){
            return $config[$key];
        }


        if($key == 1){
            return '<span class="label label-danger">'.$config[$key].'</span>';
        }else if($key == 2){
            return '<span class="label label-success">'.$config[$key].'</span>';
        }else if($key == 3){
            return '<span class="label label-default">'.$config[$key].'</span>';
        }

        return'';
    }

    /**
     * 统计红包
     * @param int $page
     * @param int $pageNumber
     * @return array
     */
    public function getStatisticsBonusLog($page = 0, $pageNumber = 0){
        $timeGap = trim(get('timegap'));
        $type = (int)get('type');
        if (!isset($timeGap)){
            // 最近1个月
            $startTime = strtotime("-1 month");
            $endTime = 0;
        }else{
            $timeGapArr = explode(' - ', $timeGap);
            $startTime = strtotime($timeGapArr[0]);
            $endTime = strtotime($timeGapArr[1]);
        }

        $iSortCol_0 = (int)get('iSortCol_0');//针对某一列进行排序
        $sSortDir_0 = trim(get('sSortDir_0'));//排序方式，值为"asc"或者"desc"

        if ($type){
            $this->db->where('b.type >= '.$type);
        }
        if ($startTime){
            $this->db->where('b.addtime >= '.$startTime);
        }
        if ($endTime){
            $endTime = strtotime('+1 day', $endTime);
            $this->db->where('b.addtime < '.$endTime);
        }

        if ($iSortCol_0 == 2){
            $this->db->order_by('b.money', $sSortDir_0); // 红包金额
        }else if($iSortCol_0 == 3){
            $this->db->order_by('b.send_number', $sSortDir_0); // 发布数量
        }else if($iSortCol_0 == 4){
            $this->db->order_by('used', $sSortDir_0); // 使用数量
        }else if($iSortCol_0 == 5){
            $this->db->order_by('not_used', $sSortDir_0); // 未使用数量
        }else if($iSortCol_0 == 6){
            $this->db->order_by('use_end', $sSortDir_0); // 失效数量
        }else if($iSortCol_0 == 7){
            $this->db->order_by('used_money', $sSortDir_0); // 使用金额
        }else if($iSortCol_0 == 8){
            $this->db->order_by('total_money', $sSortDir_0); // 红包金额
        }else if($iSortCol_0 == 9){
            $this->db->order_by('b.addtime', $sSortDir_0); // 红包金额
        }
        $t = strtotime(date('Y-m-d', time()));
        $this->db->select('b.name,b.money,b.send_number,b.type,count(if(bl.status = 1, bl.status, null)) as not_used,
        count(if(bl.status = 2, bl.status, null)) as used,sum(if(bl.status = 2, bl.money, null)) as used_money,
        sum(bl.money) as total_money,b.addtime,count(if(bl.status = 1 and b.status = 2 and b.use_end_time < '.$t.', bl.id, null)) as use_end')
            ->join($this->tbBonusLog.' bl', 'b.id=bl.bonus_id')
            ->group_by('b.id');
        if ($page && $pageNumber) {
            $tA = $this->appPage($this->tbBonus.' b', $page, false, $pageNumber);
            return $tA['list'];
        }else{
            return $this->pagination($this->tbBonus.' b');
        }

    }

    /**
     * 获取用户红包个数
     * @param int           $userId         用户id
     * @return array|int
     */
    public function getConsumerBonusNumber($userId){
        if (!$userId){
            return 0;
        }
        $time = time();
        $this->db->join($this->tbBonus.' b', 'b.id=bl.bonus_id')
            ->where(array('bl.consumer_id' => $userId, 'bl.status' => 1))
            ->where("b.use_start_time <= $time and b.use_end_time >= $time");
        return $this->count($this->tbBonusLog.' bl');
    }

    /**
     * 获取用户代金券的个数
     * @param $userId       int        用户id
     * @return array
     */
    public function getConsumerCouponNumber($userId){
        $time=  time();
        $this->db->where(array('consumer_id' => $userId, 'status' => 1))
            ->where("use_end_time >=".$time);
        return $this->count($this->tbCashCoupon);
    }
}